<?php
/**
 * 启动文件
 */
function _p($val, $die = true)
{
     header("content-Type: text/html; charset=Utf-8");  
    $out  = "<pre style=\"background: #000; color: #ccc; font: 12px 'fixedsys'; text-align: left; width: 100%; padding: 5px\">\n";
    $out .= print_r($val, true);
    $out .= "</pre>\n";
    echo $out;
    if ($die) {
       exit();
    }

   
}
/**
 * Services are globally registered in this file
 *
 * @var \Phalcon\Config $config
 */



error_reporting(E_ALL ^ E_NOTICE);


use Phalcon\Di\FactoryDefault;
use Phalcon\Mvc\View;
use Phalcon\Mvc\Url as UrlResolver;
use Phalcon\Mvc\View\Engine\Volt as VoltEngine;
use Phalcon\Mvc\Model\Metadata\Memory as MetaDataAdapter;
use Phalcon\Session\Adapter\Files as SessionAdapter;
use Phalcon\Flash\Direct as Flash;
use Phalcon\Mvc\Router;

class kernel{
    //static $base_url = null;
    static function boot(){
        try {
            /**
             * Read the configuration
             */
            global $_CONFIG;

            //$main_config = include APP_PATH . "/data/config/config.php";
            $config_datas = self::_config();
            //_p($config_datas);
            $_CONFIG = new \Phalcon\Config($config_datas['config']);
            //_p($_CONFIG);
            /**
             * Read auto-loader
             */
            $loader = new \Phalcon\Loader();
            //注册命名空间
            $loader->registerNamespaces($config_datas['registerNamespaces'])->register();
            /**
             * We're a registering a set of directories taken from the configuration file
             */
            //_p( $config_datas['registerDirs']);
            $loader->registerDirs($config_datas['registerDirs'])->register();

            /**
             * Read services
             */
            /**
             * The FactoryDefault Dependency Injector automatically register the right services providing a full stack framework
             */
            $di = new FactoryDefault();

            /**
             * The URL component is used to generate all kind of urls in the application
             */
            $di->setShared('url', function () use ($_CONFIG) {
                $url = new UrlResolver();
                $url->setBaseUri($_CONFIG->b2c->baseUri);
                return $url;
            });

            /**
             * Setting up the view component
             */
            $di->setShared('view', function () use ($_CONFIG) {

                $view = new View();

                $view->setViewsDir($_CONFIG->b2c->viewsDir);

                $view->registerEngines(array(
                    '.volt' => function ($view, $di) use ($_CONFIG) {

                        $volt = new VoltEngine($view, $di);

                        $volt->setOptions(array(
                            'compiledPath' => $_CONFIG->b2c->cacheDir,
                            'compiledSeparator' => '_'
                        ));

                        return $volt;
                    },
                    '.phtml' => 'Phalcon\Mvc\View\Engine\Php'
                ));

                return $view;
            });

            /**
             * Database connection is created based in the parameters defined in the configuration file
             */
            $di->setShared('db', function () use ($_CONFIG) {
                $dbConfig = $_CONFIG->database->toArray();
                $adapter = $dbConfig['adapter'];
                unset($dbConfig['adapter']);

                $class = 'Phalcon\Db\Adapter\Pdo\\' . $adapter;

                return new $class($dbConfig);
            });

            /**
             * If the configuration specify the use of metadata adapter use it or use memory otherwise
             */
            $di->setShared('modelsMetadata', function () {
                return new MetaDataAdapter();
            });

            /**
             * Register the session flash service with the Twitter Bootstrap classes
             */
            $di->set('flash', function () {
                return new Flash(array(
                    'error'   => 'alert alert-danger',
                    'success' => 'alert alert-success',
                    'notice'  => 'alert alert-info',
                    'warning' => 'alert alert-warning'
                ));
            });

            /**
             * Start the session the first time some component request the session service
             */
            $di->setShared('session', function () {
                $session = new SessionAdapter();
                $session->start();

                return $session;
            });
            /**
             * Add routing capabilities
             */
//            $di->set('router', function () {
//                require APP_PATH.'/config/routes.php';
//                return $router;
//            });
            $router = new Router();
            foreach ($config_datas['routes'] as $k => $v) {
                $router->add($k,$v);
            }
            
            $di->set('router', $router);
            /**
             * Handle the request
             */
           //_p($di);
            $application = new \Phalcon\Mvc\Application($di);
            //_p($di);
        //_p(  $application);
            echo $application->handle()->getContent();

        } catch (\Exception $e) {
            echo $e->getMessage() . '<br>';
            echo '<pre>' . $e->getTraceAsString() . '</pre>';
        }

    }
    /*
     * 初始数据加载处理
     */
    static function _config(){
         $main_config = unserialize(file_get_contents(APP_PATH . "/data/config/config.php"));
         //_p($main_config);
         $reutrn_datas = array();
         $reutrn_datas['routes'] = array();
         foreach ($main_config as $app => $v) {
             if($app == 'database'){//数据库配置
                 $reutrn_datas['config']['database'] = $v;
             }else{
                 $reutrn_datas['config'][$app] = array(
                    'controllersDir' => APP_PATH . '/app/'.$app.'/controller/',
                    'modelsDir'      => APP_PATH . '/app/'.$app.'/models/',
                    'migrationsDir'  => APP_PATH . '/app/'.$app.'/migrations/',
                    'viewsDir'       => APP_PATH . '/app/'.$app.'/views/',
                    'pluginsDir'     => APP_PATH . '/app/'.$app.'/plugins/',
                    'libraryDir'     => APP_PATH . '/app/'.$app.'/library/',
                    'cacheDir'       => APP_PATH . '/data/cache/'.$app.'/',
                    'baseUri'        => '/phalcon_store/',  
                 );
                 //ucwords($str)
                 $reutrn_datas['registerNamespaces'][ucwords($app).'\Controllers'] = APP_PATH."/app/".$app."/controller/";
                 $reutrn_datas['registerNamespaces'][ucwords($app).'\Models'] = APP_PATH."/app/".$app."/models/";  
                 $reutrn_datas['registerDirs'][] = array(
                     APP_PATH . '/app/'.$app.'/controller/',
                     APP_PATH . '/app/'.$app.'/models/',
                 );
                 //路由
                 $reutrn_datas['routes'] = array_merge($reutrn_datas['routes'],$v['routes']);
             }
             
         }
         return $reutrn_datas;

    }
}
